package com.supermap.client;

import com.alibaba.fastjson.JSONObject;
import com.supermap.SM2Utils;
import com.supermap.crypto.CryproType;
import com.supermap.crypto.CryptoUtils;
import com.supermap.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PublicKey;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2020/12/28 17:55
 * client消息处理类
 */
public class ClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

    private Logger logger = Logger.getLogger(ClientHandler.class.toString());

    /**
     * 处理服务端返回的数据，然后进行下一步判断
     * @param ctx
     * @param response
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) {

        int status = response.getStatus();

        /**
         *  status == 2 表示客户端在当前机器第一次发送信息给服务端，接收服务端公钥保存到本体 temp 路径下
         */
        if (status == 2) {
            // 路径设置为 java temp 路径
            String filepath = System.getProperty("java.io.tmpdir") + "/supermap_" + response.getIpfsIp().replace(".", "_") + "_" + response.getIpfsPort() + ".pem";
            File file = new File(filepath);
            if (NettyClientUtils.getCryproType() == CryproType.RSA) {
                PublicKey serverPublicKey = CryptoUtils.getRSAPublicKeyFromString(response.getPublicKey());
                NettyClientUtils.loadServerPublicKey(serverPublicKey);
                try {
                    if (!file.exists()) {
                        CryptoUtils.saveRSAPublicKeyToFile(serverPublicKey, filepath);
//                        logger.info("success save server publickey, file path is " + filepath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * status == -1 发现错误及时关闭连接
         */
        if (status == -1) {
            logger.warning( "file hash id : " + NettyClientUtils.decrypt(response.getHashId()) + " upload failed \n" + response.getError());
            ctx.channel().close();
        }

        /**
         * status == -2 表示客户端已经发送完信息并给服务端发送请求表示数据已传输完成，主动关闭客户端连接
         */
        if (status == -2) {
//            logger.info("The server has received the data and closes the connection automatically");
            ctx.channel().close();
        }

        /**
         * status == -3 客户端加载的公钥是否正确
         */
        if (status == -3) {
            // 路径设置为 java temp 路径
            String filepath = System.getProperty("java.io.tmpdir") + "/supermap_" + response.getIpfsIp().replace(".", "_") + "_" + response.getIpfsPort() + ".pem";
            logger.info("Server decryption failed, please confirm whether the server publickey key load  is correct\n" +
                    "Please delete the file :" + filepath);
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
